#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"

#include "request.pb.h"
#include <iostream>
#include <unordered_map>

class Server
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<ouyang::TranslateRequest> TranslateRequestPtr;
    typedef std::shared_ptr<ouyang::AddRequest> AddRequestPtr;
    Server(int port) : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port),
                               "Protobuf_Server", muduo::net::TcpServer::kNoReusePort),
                       _dispatcher(std::bind(&Server::onUnknownMessage, this, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3)),
                       _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,
                                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 注册业务请求的处理函数
        _dispatcher.registerMessageCallback<ouyang::TranslateRequest>(std::bind(&Server::onTranslate, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<ouyang::AddRequest>(std::bind(&Server::onAdd, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 服务器设置链接回调函数和请求回调函数
        _server.setConnectionCallback(std::bind(&Server::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void Start()
    {
        _server.start();
        _baseloop.loop();
    }

private:
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown(); // 断开连接
    }

    std::string translate(const std::string &str)
    {
        static std::unordered_map<std::string, std::string> dict_map = {
            {"Hello", "你好"},
            {"hello", "你好"},
            {"你好", "hello"}};
        auto it = dict_map.find(str);
        if (it == dict_map.end())
        {
            return "None";
        }
        return it->second;
    }

    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateRequestPtr &message, muduo::Timestamp)
    {
        // 1. 获取message中的有效信息
        std::string req_msg = message->msg();
        // 2. 对req_msg进行处理
        std::string rsp_msg = translate(req_msg);
        // 3. 组织protobuf的响应Response
        ouyang::TranslateResponse resp;
        resp.set_msg(rsp_msg);
        // 4. 发送响应
        _codec.send(conn, resp);
    }

    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddRequestPtr &message, muduo::Timestamp)
    {
        // 1. 获取message中的有效信息
        int num1 = message->num1();
        int num2 = message->num2();
        // 2. 对num1, num2进行处理
        int ret = num1 + num2;
        // 3. 组织protobuf的响应Response
        ouyang::AddResponse resp;
        resp.set_result(ret);
        // 4. 发送响应
        _codec.send(conn, resp);
    }

    // 用于链接的回调函数，这个链接回调函数在新链接建立和链接关闭时调用
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected() == false)
        {
            LOG_INFO << "新链接建立成功!\n";
        }
        else
        {
            LOG_INFO << "新链接关闭成功!\n";
        }
    }

private:
    muduo::net::EventLoop _baseloop; // 事件循环，不断监听是否有事件发生，并且分发IO事件
    muduo::net::TcpServer _server;   // 服务器对象
    ProtobufDispatcher _dispatcher;  // 请求器分发对象 --> 需要向其中注册请求函数
    ProtobufCodec _codec;            // protobuf协议处理器 --> 针对收到的请求数据进行protobuf协议处理
};

int main()
{
    Server server(8085);
    server.Start();
    return 0;
}